package android.slc.base.api.slc.interceptor;

import android.slc.box.or.ApiConstants;
import android.slc.base.api.slc.config.ApiConfig;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Headers headers = request.headers();
        boolean isHaveContentType = false, isHaveToken = false;
        for (int i = 0; i < headers.size(); i++) {
            String name = headers.name(i);
            if (ApiConstants.KEY_CONTENT_TYPE.equals(name)) {
                isHaveContentType = true;
            } else if (ApiConfig.Key.KEY_TOKEN.equals(name)) {
                isHaveToken = true;
            }
        }
        Request.Builder requestBuilder = request.newBuilder();
        if (!isHaveContentType) {
            requestBuilder.addHeader(ApiConstants.KEY_CONTENT_TYPE, ApiConstants.VALUE_APPLICATION_JSON);
        }
        if (!isHaveToken && ApiConfig.getInstance().getToken() != null) {
            requestBuilder.addHeader(ApiConfig.Key.KEY_TOKEN, ApiConfig.getInstance().getToken());
        }
        request = requestBuilder.build();
        return chain.proceed(request);
    }

}
